import DList from "@/components/dlist";
import DConnectCustomerService from "@/components/other/common/DConnectCustomerService";
import serviceCard from "./service_card";
import cTitle from "components/title";
import { Toast } from "vant";

export default {
  data() {
    return {
      isHideStore: 0,
      active: 2,
      address: "",
      lng: "",
      lat: "",
      location: "",
      incompleteList: [],
      // 未完成
      upgradeCodePage: 1,
      loading: false,
      finished: false,
      // 已完成
      upgradeCodePage_completed: 1,
      loading_completed: false,
      finished_completed: false,
      completed: [],
      // tab切换
      tabsShow: true,
      projectName: "",
      titled: "",
      titleIng: "",
      // 赠送
      giveInfo: '',
      showGivePop: false,
      nickname: '',
      giveUserId: '',
      giveNum: '',
      errorNum: '',
      // 排序
      orderby:0,
      orderbyList:[{
        name:'购买时间',
        state:'drop',
      },{
        name:'到期时间',
        state:'',
      }],
      // 预约弹窗
      showAppointment:false,
      // 预约选择门店弹窗
      showAppointment_Store:false,
      Appointment_Store:{
        page:1,
        last_page:0,
        keyword:'',
        radio:'',
        list:[],
        project_id:'',
        timeList:[],
        selectTime:'',
        DaySelect:new Date()
      },
      // 预约选择预约时间
      showAppointment_Time:false,
      showAppointment_Time_select:false,
      minDate: new Date(),
      maxDate: new Date(2025, 10, 1),
      // currentDate: new Date(),
    };
  },
  watch: {
    "$route"(to, from) {
      if (from.name === "MoreStores" && to.name === "MyProject") {
        this.$router.go(0);
      }
      if (from.name === "StoreVerification") {
        this.$router.go(0);
      }
    }
  },
  activated() {
    this.projectName = this.fun.getCustomTextLang("store_projects.project", "项目");
    this.titled = "可使用" + this.projectName;
    this.titleIng = "已完成" + this.projectName;
    this.active = '';
    this.fun.getLocation()
      .then(res => {
        this.location = res;
        this.address = res.title;
        this.initData();
        this.getIncomplete();
      })
      .catch(err => {
        console.log(err);
      });
    this.initAppointment_Store();
    let maxYear = new Date().getFullYear() + 10;
    this.maxDate = new Date(maxYear,1,1);
  },
  computed: {
    storeNameCheck() {
      let name = "";
      let list = this.Appointment_Store.list;
      for (let i = 0; i < list.length; i++) {
        if (list[i].id == this.Appointment_Store.radio) {
          name = list[i].store_name;
        }
      }
      return name;
    },
    timeClass(item){
      return function(item){
        if(item.is_full){
          return 'full'
        }else if(item.id == this.Appointment_Store.selectTime){
          return 'select'
        }
      }
    },
    timeFittle(){
      return this.fun.dateFormat("YYYYmmdd", this.Appointment_Store.DaySelect);
    },
    selectTime_Fittle(){
      let str = '';
      if(this.timeList.length <= 0) return
      for (let i = 0; i < this.timeList.length; i++) {
        console.log(this.timeList)
        if(this.timeList[i].id == this.Appointment_Store.selectTime){
          str = `${this.timeList[i].start_hour}-${this.timeList[i].end_hour}`
        }
      }
      return str
    }
  },
  methods: {
    // async expectGet(){

    // },
    initAppointment_Store(){
      this.Appointment_Store.page = 1;
      this.Appointment_Store.last_page = 0;
      this.Appointment_Store.keyword = "";
      this.Appointment_Store.radio = "";
      this.Appointment_Store.list = [];
      this.Appointment_Store.project_id = "";
      this.Appointment_Store.timeList = [];
      this.Appointment_Store.selectTime = "";
      this.Appointment_Store.DaySelect = new Date();
      this.showAppointment_Time = false;
      this.showAppointment_Time_select = false;
      this.showAppointment_Store = false;
    },
    toLink(){
      this.$router.push(this.fun.getUrl("WriteOffRecord", {}));
    },
    async showAppointmentOpen(item) {
      let project_id = this.Appointment_Store.project_id ? this.Appointment_Store.project_id : item.id;
      this.Appointment_Store.project_id = project_id;
      let json = { plugin_order_id: project_id, store_name: this.Appointment_Store.keyword };
      let { msg, data, result } = await $http.post("plugin.store-projects.frontend.expect.expectData", json, ".");
      if (!result) {
        this.$toast(msg)
        return
      };
      this.Appointment_Store.list = data.store_list.data;
      this.Appointment_Store.page = 1;
      this.Appointment_Store.last_page = data.store_list.last_page;
      this.showAppointment = true;
    },
    async TapMore(){
      this.Appointment_Store.page = this.Appointment_Store.page + 1;
      let json = {
        plugin_order_id: this.Appointment_Store.project_id,
        store_name: this.Appointment_Store.keyword,
        page:this.Appointment_Store.page,
      };
      let { msg, data, result } = await $http.post("plugin.store-projects.frontend.expect.expectData", json, ".");
      if (!result) return this.$toast(msg);
      this.Appointment_Store.list = data.store_list.data;
    },
    async showAppointment_TimeOpen(){
      let now = Date.parse(this.Appointment_Store.DaySelect) / 1000;
      now = this.timestampToTime(now);
      if(!this.Appointment_Store.radio) return this.$toast('请先选择门店');
      let json = {
        plugin_order_id: this.Appointment_Store.project_id,
        store_id: String(this.Appointment_Store.radio),
        day:now
      };
      let { msg, data, result } = await $http.post("plugin.store-projects.frontend.expect.expectTimeList", json, ".");
      if (!result){
        this.$toast(msg);
        this.Appointment_Store.selectTime = "";
        this.timeList = [];
        return
      };
      if(data.length > 0){
        this.showAppointment_Time = true;
        this.timeList = data;
      }
    },
    async time_confirm(){
      await this.showAppointment_TimeOpen()
      this.showAppointment_Time_select = false;
    },
    time_cancel(){
      this.showAppointment_Time_select = false;
    },
    tapStoreTime(item){
      if(item.is_full == 1) return;
      if(item.id == this.Appointment_Store.selectTime){
        this.Appointment_Store.selectTime = '';
        return
      }
      this.Appointment_Store.selectTime = item.id;
    },
    tapStore(item) {
      if(this.Appointment_Store.radio == item.id){
        this.Appointment_Store.radio = [];
        return
      }
      this.Appointment_Store.radio = [item.id];
      if(item.expect_days > 0){
        this.maxDate = new Date(new Date().getTime() + (item.expect_days * 24 * 60 * 60 * 1000))
      }
    },
    onSearch() {
      this.Appointment_Store.radio = [];
      this.Appointment_Store.page = 1;
      this.Appointment_Store.last_page = 0;
      this.Appointment_Store.list = [];
      this.showAppointmentOpen();
    },
    onClickLeft1() {
      this.showAppointment_Store = false;
      if(!this.Appointment_Store.radio){
        this.Appointment_Store.radio = "";
      }
      this.Appointment_Store.page = 1;
      this.Appointment_Store.last_page = 0;
    },
    onClickLeft() {
      this.showAppointment_Time = false;
    },
    onClickRight() {
      this.showAppointment_Time = false;
    },
    // 选择门店弹窗
    onClickRight1(){
      this.showAppointment_Store = false;
      if(this.Appointment_Store.radio.length == 0){
        this.Appointment_Store.radio = "";
      }
    },
    timestampToTime: function(timestamp) {
      if (!Number(timestamp) || timestamp == "") {
        return "";
      }
      let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear();
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) ;
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
      return `${Y}${M}${D}`;
    },
    showAppointment_Tap_Cancel(){
      this.Appointment_Store.radio = "";
      this.Appointment_Store.selectTime = "";
      this.Appointment_Store.page = 1;
      this.Appointment_Store.last_page = 0;
      this.Appointment_Store.project_id = "";
      this.showAppointment = false;
    },
    async showAppointment_Tap_confirm(){
      if(!this.Appointment_Store.radio){
        this.$toast("请选择门店")
        return
      }
      if(!this.Appointment_Store.selectTime){
        this.$toast('请选择预约时间');
        return
      }
      let json = {
        plugin_order_id: this.Appointment_Store.project_id,
        expect_set_id: this.Appointment_Store.selectTime,
        store_id:String(this.Appointment_Store.radio),
        day:this.fun.dateFormat("YYYYmmdd", this.Appointment_Store.DaySelect)
      };
      let { msg, data, result } = await $http.post("plugin.store-projects.frontend.expect.expect", json, ".");
      if (!result) {
        this.$toast(msg);
        return
      };
      console.log(data)
      this.$toast(msg);
      this.showAppointment = false;
    },
    to_project_detail(id){
      this.$router.push(this.fun.getUrl("VerificationProjectDetails", { id }));
    },
    initData() {
      this.upgradeCodePage = 1;
      this.upgradeCodePage_completed = 1;
      this.loading = false;
      this.loading_completed = false;
      this.finished = false;
      this.finished_completed = false;
      this.incompleteList = [];
      this.completed = [];
    },
    // 获取未完成项目列表
    getIncomplete() {
      if (!this.location) {
        return;
      }
      this.loading = true;
      let p = this.fun.bd_encrypt(this.location.point.lng, this.location.point.lat);
      this.lng = p.lng;
      this.lat = p.lat;
      let _json = {
        lng: this.lng,
        lat: this.lat,
        page: this.upgradeCodePage,
        orderby:this.orderby
      }
      if(this.$route.query.order_id){
        _json.order_id = this.$route.query.order_id;
      }
      $http
        .get("plugin.store-projects.frontend.project-order.get-un-finish-list",_json )
        .then(response => {
          if (response.result === 1) {
            const { data: data, current_page, last_page } = response.data;
            if (data.length === 0 || current_page === last_page) {
              this.finished = true;
            }
            this.loading = false;
            this.incompleteList.push(...data);
            this.upgradeCodePage++;
          } else {
            Toast(response.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取已完成数据
    getCompleted() {
      // if(this.loading_completed ){ return; }
      this.loading_completed = true;
      $http
        .get("plugin.store-projects.frontend.project-order.get-finish-list", { page: this.upgradeCodePage_completed }, "load")
        .then(response => {
          if (response.result === 1) {
            const { data: data, current_page, last_page } = response.data;
            if (data.length === 0 || current_page === last_page) {
              this.finished_completed = true;
            }
            this.loading_completed = false;
            this.completed.push(...data);
            this.upgradeCodePage_completed++;
          } else {
            Toast(response.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 跳转会员核销页面
    btnVerUser(data) {
      this.$router.push(this.fun.getUrl("WriteOffRecord", { project_title: data }));
    },
    //跳转核销使用
    btnUsere(data) {
      this.$router.push(this.fun.getUrl("WriteOff", { item: data }));
    },
    // 点击跳转查看更多商户
    seeMore(data) {
      this.initData();
      this.$router.push(this.fun.getUrl("MoreStores", { id: data.id, project_id: data.project_id, name: "myProject" }));
    },
    // van-tabs选中状态
    btnSelect(data) {
      this.initData();
      if (data === 1) {

        // this.upgradeCodePage_completed = 1
        this.loading_completed = false;
        this.finished_completed = false;
        this.tabsShow = false;
        // this.completed = []
        this.getCompleted();
      } else {
        // this.upgradeCodePage = 1
        this.loading = false;
        this.finished = false;
        this.tabsShow = true;
        // this.incompleteList = []
        this.getIncomplete();
      }
    },
    btnValue(data) {
      this.value = data;
    },
    tolocation() {
      this.$store.commit("setReferer", window.location.href);
      this.$router.push(this.fun.getUrl("o2oLocation"));
    },

    tapBtnGive (obj) {
      this.showGivePop = true;
      this.giveInfo = obj;
    },
    // 关闭弹框
    closeGivePop () {
      this.showGivePop = false;
      this.errorNum = '';
      this.giveUserId = '';
      this.giveNum = '';
    },
    throttleFn(event) {
      if (this.timeoutId) {
        clearTimeout(this.timeoutId);
      }
      let that = this;
      this.timeoutId = setTimeout(function () {
        that.searchUser(event);
      }, 800);
    },
    changeNumInput (event) {
      console.log(event);
      let num = event * 1;
      if (this.fun.isTextEmpty(num)) {
        this.errorNum = "转增次数不能为空";
        return;
      }
      console.log(this.giveInfo.rest_count, num);
      if (this.giveInfo.rest_count < num) {
        this.errorNum = "输入转赠次数大于拥有的次数";
        return;
      }
      this.errorNum = '';
    },
    // 搜索用户
    searchUser (event) {
      this.nickname = null;
      var reSearch = event.target.value;
      if (reSearch) {
        $http.get("member.member.memberInfo", { uid: reSearch }, "loading")
          .then(response => {
            if (response.result === 1) {
              this.giveUserId = reSearch;
              this.nickname = response.data ? response.data.nickname : '查无此用户';
            } else {
              this.nickname = null;
              Toast(response.msg);
            }
          })
          .catch(error => {
            this.giveUserId = '';
          });
      } else {
        this.nickname = "用户id不能为空";
      }
    },

    // 赠送
    giveProject() {
      if (!this.giveUserId) {
        this.nickname = "用户id不能为空";
        return;
      }
      if (this.nickname === '查无此用户') {
        return;
      }
      if (!this.giveNum) {
        this.errorNum = "转增次数不能为空";
        return;
      }
      if (this.giveInfo.rest_count < this.giveNum) {
        this.errorNum = "输入转赠次数大于拥有的次数";
        return;
      }

      $http.get("plugin.store-projects.frontend.project-order.transfer",
        {
          id: this.giveInfo.id,
          transfer_uid: this.giveUserId,
          transfer_count: this.giveNum
        }, "赠送中")
        .then((res) => {
          if (res.result !== 1) {
            Toast(res.msg);
          }
          this.initData();
          this.loading_completed = false;
          this.finished_completed = false;
          this.tabsShow = false;
          this.getIncomplete();
          this.closeGivePop();
          Toast('赠送成功');
        });
    },

    // 排序
    orderBy(name,state){
      // 排序方式:0-购买时间降序,1-购买时间升序,2-到期时间降序,3-到期时间升序
      if(name == '购买时间'){
        this.orderbyList[0].state = state;
        this.orderbyList[1].state = '';
        if(state == 'rise'){
          this.orderby = '1';
        }else{
          this.orderby = '0';
        }
      }
      if(name == '到期时间'){
        this.orderbyList[1].state = state;
        this.orderbyList[0].state = '';
        if(state == 'rise'){
          this.orderby = '3';
        }else{
          this.orderby = '2';
        }
      }
      this.initData();
      this.getIncomplete();
    },
    hide_store(e){
      this.isHideStore = !e;
    }
  },
  components: { DList, DConnectCustomerService, serviceCard, cTitle }
};
